<template>
  <div class="h-screen flex">
    <!-- 左侧蓝色区域 -->
    <div class="gradient-bg w-1/2 text-white p-12 flex flex-col justify-center items-center text-center relative">
      <div class="w-24 h-24 rounded-full mb-8 overflow-hidden" :class="{ 'bg-white': !logoUrl }">
        <template v-if="logoUrl">
          <img :src="logoUrl" alt="品牌图" class="w-full h-full object-cover" />
        </template>
      </div>
      <h1 class="text-4xl font-bold mb-4">快递到了吗</h1>
      <p class="text-lg mb-16 opacity-90">安全、快捷、方便的快递代拿体验，让校园生活更轻松</p>

      <div class="space-y-8 w-full max-w-xl text-left">
        <div class="flex items-start gap-4">
          <div class="w-12 h-12 bg-white bg-opacity-20 rounded-lg flex items-center justify-center flex-shrink-0">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 1.944A11.954 11.954 0 012.166 5C2.056 5.649 2 6.319 2 7c0 5.225 3.34 9.67 8 11.317C14.66 16.67 18 12.225 18 7c0-.682-.057-1.35-.166-2.001A11.954 11.954 0 0110 1.944zM11 14a1 1 0 11-2 0 1 1 0 012 0zm0-7a1 1 0 10-2 0v3a1 1 0 102 0V7z" clip-rule="evenodd"/></svg>
          </div>
          <div>
            <h3 class="font-semibold text-lg mb-1">安全保障</h3>
            <p class="text-sm opacity-80">实名认证，全程追踪，保障您的快递安全</p>
          </div>
        </div>

        <div class="flex items-start gap-4">
          <div class="w-12 h-12 bg-white bg-opacity-20 rounded-lg flex items-center justify-center flex-shrink-0">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20"><path d="M8 16.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0zM15 16.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0z"/><path d="M3 4a1 1 0 00-1 1v10a1 1 0 001 1h1.05a2.5 2.5 0 014.9 0H10a1 1 0 001-1V5a1 1 0 00-1-1H3zM14 7a1 1 0 00-1 1v6.05A2.5 2.5 0 0115.95 16H17a1 1 0 001-1v-5a1 1 0 00-.293-.707l-2-2A1 1 0 0015 7h-1z"/></svg>
          </div>
          <div>
            <h3 class="font-semibold text-lg mb-1">快速配送</h3>
            <p class="text-sm opacity-80">校内专人配送，最快30分钟送达</p>
        </div>
      </div>

        <div class="flex items-start gap-4">
          <div class="w-12 h-12 bg-white bg-opacity-20 rounded-lg flex items-center justify-center flex-shrink-0">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20"><path d="M2 3a1 1 0 011-1h2.153a1 1 0 01.986.836l.74 4.435a1 1 0 01-.54 1.06l-1.548.773a11.037 11.037 0 006.105 6.105l.774-1.548a1 1 0 011.059-.54l4.435.74a1 1 0 01.836.986V17a1 1 0 01-1 1h-2C7.82 18 2 12.18 2 5V3z"/></svg>
          </div>
          <div>
            <h3 class="font-semibold text-lg mb-1">便捷操作</h3>
            <p class="text-sm opacity-80">在线下单，实时追踪，一键完成代拿服务</p>
          </div>
        </div>
        </div>
      </div>

    <!-- 右侧白色登录区域 -->
    <div class="w-1/2 bg-gray-50 p-12 flex flex-col justify-center">
      <div class="max-w-md mx-auto w-full">
        <h2 class="text-3xl font-bold text-gray-800 mb-2">欢迎回来</h2>
        <p class="text-gray-500 mb-8">请登录您的账号继续使用服务</p>

        <div class="flex gap-6 mb-8 border-b">
          <button class="pb-3" :class="loginMethod==='sms' ? 'text-blue-600 border-b-2 border-blue-600 font-medium' : 'text-gray-500 hover:text-gray-700'" @click="loginMethod='sms'">验证码登录</button>
          <button class="pb-3" :class="loginMethod==='password' ? 'text-blue-600 border-b-2 border-blue-600 font-medium' : 'text-gray-500 hover:text-gray-700'" @click="loginMethod='password'">密码登录</button>
        </div>

        <form class="space-y-6" @submit.prevent="loginMethod==='sms' ? handleSmsLogin() : handlePasswordLogin()">
          <div v-if="loginMethod==='sms'">
            <label class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
            <div class="relative">
              <span class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400">
                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path d="M2 3a1 1 0 011-1h2.153a1 1 0 01.986.836l.74 4.435a1 1 0 01-.54 1.06l-1.548.773a11.037 11.037 0 006.105 6.105l.774-1.548a1 1 0 011.059-.54l4.435.74a1 1 0 01.836.986V17a1 1 0 01-1 1h-2C7.82 18 2 12.18 2 5V3z"/></svg>
              </span>
              <input type="tel" v-model="phone" placeholder="请输入手机号" maxlength="11" class="w-full pl-12 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none" />
            </div>
          </div>

          <div v-if="loginMethod==='sms'">
            <label class="block text-sm font-medium text-gray-700 mb-2">验证码</label>
            <div class="flex gap-3">
              <div class="relative flex-1">
                <span class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400">
                  <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M18 8a6 6 0 01-7.743 5.743L10 14l-1 1-1 1H6v2H2v-4l4.257-4.257A6 6 0 1118 8zm-6-4a1 1 0 100 2 2 2 0 012 2 1 1 0 102 0 4 4 0 00-4-4z" clip-rule="evenodd"/></svg>
                </span>
                <input type="text" v-model="smsCode" placeholder="请输入验证码" maxlength="6" class="w-full pl-12 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none" />
              </div>
              <button type="button" class="px-6 py-3 border border-blue-600 text-blue-600 rounded-lg hover:bg-blue-50 transition whitespace-nowrap" :disabled="countdown>0" @click="getVerificationCode">
                {{ countdown > 0 ? `重新发送(${countdown}s)` : '获取验证码' }}
              </button>
            </div>
          </div>

          <div v-if="loginMethod==='password'">
            <label class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
            <input type="tel" v-model="passwordPhone" placeholder="请输入手机号" maxlength="11" class="w-full pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none" />
        </div>

          <div v-if="loginMethod==='password'">
            <label class="block text-sm font-medium text-gray-700 mb-2">密码</label>
            <input type="password" v-model="password" placeholder="请输入密码" class="w-full pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none" />
          </div>

          <button type="submit" class="w-full py-3 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition">登录</button>

          <div class="flex justify-between text-sm">
            <a href="#" class="text-blue-600 hover:underline" @click.prevent="showForgetPassword">忘记密码</a>
            <a href="#" class="text-blue-600 hover:underline" @click.prevent="showHelp">遇到问题</a>
          </div>
        </form>

        <div class="mt-8 text-center">
          <span class="text-gray-600">还没有账号？</span>
          <button class="ml-2 px-6 py-2 border border-blue-600 text-blue-600 rounded-lg hover:bg-blue-50 transition" @click="goToRegister">立即注册</button>
          </div>

        

        <!-- 微信扫码登录弹窗 -->
        <div v-if="showWechatModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" @click.self="closeWechatModal">
          <div class="bg-white rounded-lg p-8 max-w-md w-full mx-4 relative">
            <!-- 关闭按钮 -->
            <button @click="closeWechatModal" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
              </svg>
            </button>
            
            <!-- 标题 -->
            <div class="text-center mb-6">
              <h3 class="text-2xl font-bold text-gray-900 mb-2">微信扫码登录</h3>
              <p class="text-gray-500 text-sm">请使用微信扫描二维码登录</p>
            </div>

            <!-- 二维码区域 -->
            <div class="flex justify-center mb-6">
              <div class="relative">
                <div v-if="qrCodeLoading" class="w-64 h-64 flex items-center justify-center bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
                  <div class="text-center">
                    <svg class="animate-spin h-8 w-8 text-blue-600 mx-auto mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                      <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                      <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <p class="text-gray-500 text-sm">生成二维码中...</p>
                  </div>
                </div>
                <div v-else-if="qrCodeError" class="w-64 h-64 flex items-center justify-center bg-red-50 rounded-lg border-2 border-red-300">
                  <div class="text-center">
                    <svg class="w-12 h-12 text-red-500 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    <p class="text-red-600 text-sm mb-2">二维码生成失败</p>
                    <button @click="generateQRCode" class="text-blue-600 hover:underline text-sm">重新生成</button>
                  </div>
                </div>
                <div v-else class="relative">
                  <div ref="qrcodeContainer" class="w-64 h-64 bg-white rounded-lg border-2 border-gray-200 p-4 flex items-center justify-center">
                    <!-- 二维码将在这里渲染 -->
                  </div>
                  <!-- 二维码过期提示 -->
                  <div v-if="qrCodeExpired" class="absolute inset-0 bg-black bg-opacity-50 rounded-lg flex items-center justify-center">
                    <div class="text-center text-white p-4">
                      <p class="mb-2">二维码已过期</p>
                      <button @click="generateQRCode" class="px-4 py-2 bg-white text-gray-900 rounded hover:bg-gray-100">点击刷新</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 扫码提示 -->
            <div class="text-center mb-6">
              <div class="flex items-center justify-center gap-2 text-gray-600 text-sm mb-2">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/>
                </svg>
                <span>打开微信扫一扫</span>
              </div>
              <p class="text-gray-500 text-xs">扫描上方二维码即可快速登录</p>
            </div>

            <!-- 登录状态提示 -->
            <div v-if="scanStatus !== 'waiting'" class="mb-4">
              <div v-if="scanStatus === 'scanned'" class="bg-blue-50 border border-blue-200 rounded-lg p-4 text-center">
                <div class="flex items-center justify-center gap-2 text-blue-700 mb-1">
                  <svg class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                  </svg>
                  <span class="font-medium">已扫码，等待确认</span>
                </div>
              </div>
              <div v-if="scanStatus === 'confirmed'" class="bg-green-50 border border-green-200 rounded-lg p-4 text-center">
                <div class="flex items-center justify-center gap-2 text-green-700">
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                  </svg>
                  <span class="font-medium">登录成功！</span>
                </div>
              </div>
            </div>
          </div>
      </div>

        <div class="mt-12 text-center text-xs text-gray-400">
          <p>© 2023 校园快递代拿 版权所有 | 隐私政策 | 使用条款</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import registerLogo from '@/../头像.jpg'

export default {
  name: 'Login',
  data() {
    return {
      logoUrl: registerLogo || '',
      loginMethod: 'sms', // 'sms' 或 'password'
      // 验证码登录字段
      phone: '',
      smsCode: '',
      countdown: 0,
      timer: null,
      // 密码登录字段
      passwordPhone: '',
      password: '',
      // 微信登录相关
      showWechatModal: false,
      qrCodeLoading: false,
      qrCodeError: false,
      qrCodeExpired: false,
      qrCodeToken: null,
      scanStatus: 'waiting', // 'waiting', 'scanned', 'confirmed'
      pollTimer: null,
      qrcodeContainer: null
    }
  },
  methods: {
    // 获取验证码
    async getVerificationCode() {
      // 更宽松的手机号验证：11位数字，以1开头
      const phoneRegex = /^1\d{10}$/
      const phone = this.phone

      if (!phone) {
        ElMessage.warning('请输入手机号')
        return
      }

      if (!phoneRegex.test(phone)) {
        ElMessage.warning('请输入正确的11位手机号（以1开头）')
        return
      }

      try {
        const response = await fetch('/api/auth/send-sms', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ phone })
        })

        const result = await response.json()

        if (result.success) {
          // 获取验证码（优先使用 debugCode，兼容 smsCode）
          const verificationCode = result.data?.debugCode || result.data?.smsCode || ''
          
          // 显示验证码消息（开发模式下显示验证码）
          if (verificationCode) {
            ElMessage({
              message: `验证码已发送: ${verificationCode}`,
              type: 'success',
              duration: 5000,
              showClose: true
            })
          } else {
            ElMessage.success(result.message || '验证码已发送')
          }
          
          // 开始倒计时
          this.countdown = 60
          this.timer = setInterval(() => {
            this.countdown--
            if (this.countdown <= 0) {
              clearInterval(this.timer)
            }
          }, 1000)
        } else {
          ElMessage.error(result.message || '发送验证码失败')
        }
      } catch (error) {
        console.error('发送验证码错误:', error)
        ElMessage.error('网络错误，请重试')
      }
    },

    // 验证码登录
    async handleSmsLogin() {
      if (!this.phone) {
        ElMessage.warning('请输入手机号')
        return
      }

      if (!this.smsCode) {
        ElMessage.warning('请输入验证码')
        return
      }

      try {
        const response = await fetch('/api/auth/login-with-sms', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            phone: this.phone,
            smsCode: this.smsCode
          })
        })

        const result = await response.json()

        if (result.success) {
          await this.handleLoginSuccess(result.data.userId, this.phone)
        } else {
          // 如果是未注册用户，提示注册
          if (result.code === 'USER_NOT_REGISTERED') {
            ElMessage.warning('该手机号未注册，请先注册')
            this.goToRegister()
          } else {
            ElMessage.error(result.message || '登录失败')
          }
        }
      } catch (error) {
        console.error('验证码登录错误:', error)
        ElMessage.error('网络错误，请重试')
      }
    },

    // 密码登录
    async handlePasswordLogin() {
      if (!this.passwordPhone) {
        ElMessage.warning('请输入手机号')
        return
      }

      if (!this.password) {
        ElMessage.warning('请输入密码')
        return
      }

      try {
        const response = await fetch('/api/auth/login-with-password', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            phone: this.passwordPhone,
            password: this.password
          })
        })

        const result = await response.json()

        if (result.success) {
          await this.handleLoginSuccess(result.data.userId, this.passwordPhone, result.data.userInfo)
        } else {
          ElMessage.error(result.message || '登录失败')
        }
      } catch (error) {
        console.error('密码登录错误:', error)
        ElMessage.error('网络错误，请重试')
      }
    },

    // 登录成功处理
    async handleLoginSuccess(userId, phone, userInfo = null) {
      ElMessage.success('登录成功！')
      
      // 保存基础用户信息
      localStorage.setItem('userToken', 'user-token-' + userId)
      localStorage.setItem('userId', userId)
      localStorage.setItem('userPhone', phone)
      
      // 如果有用户信息，直接保存
      if (userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        localStorage.setItem('userNickname', userInfo.nickname || '')
        localStorage.setItem('userAvatar', userInfo.avatarUrl || '')
      } else {
        // 否则获取完整的用户信息
        await this.fetchUserProfile(userId)
      }
      
      // 跳转到身份选择主页
      this.$router.push('/identity')
    },

    // 获取用户完整信息
    async fetchUserProfile(userId) {
      try {
        const response = await fetch(`/api/users/profile/${userId}`)
        const result = await response.json()
        
        if (result.success && result.data) {
          const userData = result.data
          // 保存用户完整信息，包括头像
          localStorage.setItem('userInfo', JSON.stringify(userData))
          localStorage.setItem('userNickname', userData.nickname || '')
          // 优先保存avatar_url，如果没有则保存avatar
          localStorage.setItem('userAvatar', userData.avatar_url || userData.avatar || '')
          
          // 保存用户身份信息
          if (userData.order_profile || result.data.order_user) {
            const orderUser = userData.order_profile || result.data.order_user
            if (orderUser && orderUser.id) {
              localStorage.setItem('orderUserId', orderUser.id)
            }
          }
          if (userData.courier_profile || result.data.courier_user) {
            const courierUser = userData.courier_profile || result.data.courier_user
            if (courierUser && courierUser.id) {
              localStorage.setItem('courierUserId', courierUser.id)
            }
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    },

    // 跳转到注册页面
    goToRegister() {
      this.$router.push('/register')
    },

    // 忘记密码
    showForgetPassword() {
      if (this.loginMethod === 'password') {
        ElMessage.info('忘记密码功能开发中...')
      } else {
        ElMessage.info('请切换到密码登录使用忘记密码功能')
      }
    },

    // 帮助
    showHelp() {
      ElMessage.info('请联系客服：400-123-4567')
    },

    // 显示微信扫码登录弹窗
    async showWechatQRCode() {
      this.showWechatModal = true
      await this.generateQRCode()
    },

    // 关闭微信登录弹窗
    closeWechatModal() {
      this.showWechatModal = false
      this.qrCodeExpired = false
      this.scanStatus = 'waiting'
      if (this.pollTimer) {
        clearInterval(this.pollTimer)
        this.pollTimer = null
      }
      this.qrCodeToken = null
    },

    // 生成二维码
    async generateQRCode() {
      this.qrCodeLoading = true
      this.qrCodeError = false
      this.qrCodeExpired = false
      this.scanStatus = 'waiting'

      try {
        // 请求后端生成二维码
        const response = await fetch('/api/auth/wechat/qrcode', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        })

        const result = await response.json()

        if (result.success) {
          this.qrCodeToken = result.data.token
          const qrCodeUrl = result.data.qrCodeUrl || result.data.url

          // 动态加载 qrcode 库并生成二维码
          await this.renderQRCode(qrCodeUrl)

          // 开始轮询扫码状态
          this.startPolling()

          // 设置二维码过期时间（通常为5分钟）
          setTimeout(() => {
            if (this.showWechatModal && this.scanStatus === 'waiting') {
              this.qrCodeExpired = true
              if (this.pollTimer) {
                clearInterval(this.pollTimer)
                this.pollTimer = null
              }
            }
          }, 5 * 60 * 1000)
        } else {
          throw new Error(result.message || '生成二维码失败')
        }
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.qrCodeError = true
        ElMessage.error('生成二维码失败，请重试')
      } finally {
        this.qrCodeLoading = false
      }
    },

    // 渲染二维码
    async renderQRCode(url) {
      try {
        // 使用 qrcode-generator 库（更轻量）
        if (!window.qrcode) {
          const script = document.createElement('script')
          script.src = 'https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js'
          await new Promise((resolve, reject) => {
            script.onload = resolve
            script.onerror = reject
            document.head.appendChild(script)
          })
        }

        // 清空容器
        if (this.$refs.qrcodeContainer) {
          this.$refs.qrcodeContainer.innerHTML = ''
          
          // 使用 qrcode.js 生成二维码到 canvas
          const canvas = document.createElement('canvas')
          this.$refs.qrcodeContainer.appendChild(canvas)
          
          await QRCode.toCanvas(canvas, url, {
            width: 256,
            margin: 2,
            color: {
              dark: '#000000',
              light: '#FFFFFF'
            }
          })
        }
      } catch (error) {
        console.error('渲染二维码失败:', error)
        // 如果加载失败，使用在线API生成二维码图片
        if (this.$refs.qrcodeContainer) {
          this.$refs.qrcodeContainer.innerHTML = `
            <img src="https://api.qrserver.com/v1/create-qr-code/?size=256x256&data=${encodeURIComponent(url)}" 
                 alt="微信登录二维码" 
                 class="w-full h-full object-contain" />
          `
        }
      }
    },

    // 开始轮询扫码状态
    startPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer)
      }

      // 检查URL参数（微信回调后可能有wechat_success参数）
      const urlParams = new URLSearchParams(window.location.search)
      if (urlParams.get('wechat_success') === 'true') {
        const state = urlParams.get('state')
        if (state === this.qrCodeToken) {
          // 立即检查一次状态
          this.checkWechatStatus()
        }
      }

      this.pollTimer = setInterval(async () => {
        if (!this.qrCodeToken || !this.showWechatModal) {
          clearInterval(this.pollTimer)
          return
        }

        await this.checkWechatStatus()
      }, 2000) // 每2秒轮询一次
    },

    // 检查微信扫码状态
    async checkWechatStatus() {
      try {
        const response = await fetch(`/api/auth/wechat/check?token=${this.qrCodeToken}`)
        const result = await response.json()

        if (result.success) {
          if (result.data.status === 'scanned') {
            this.scanStatus = 'scanned'
          } else if (result.data.status === 'confirmed') {
            this.scanStatus = 'confirmed'
            if (this.pollTimer) {
              clearInterval(this.pollTimer)
              this.pollTimer = null
            }
            
            // 登录成功
            await this.handleWechatLoginSuccess(result.data)
          } else if (result.data.status === 'expired') {
            this.qrCodeExpired = true
            if (this.pollTimer) {
              clearInterval(this.pollTimer)
              this.pollTimer = null
            }
          }
        }
      } catch (error) {
        console.error('检查扫码状态失败:', error)
      }
    },

    // 微信登录成功处理
    async handleWechatLoginSuccess(data) {
      ElMessage.success('微信登录成功！')
      
      const userId = data.userId || data.user_id
      const userInfo = data.userInfo || data.user_info

      // 保存用户信息
      localStorage.setItem('userToken', 'user-token-' + userId)
      localStorage.setItem('userId', userId)
      
      if (userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        localStorage.setItem('userNickname', userInfo.nickname || '微信用户')
        localStorage.setItem('userAvatar', userInfo.avatar || userInfo.avatarUrl || '')
      }

      // 关闭弹窗
      setTimeout(() => {
        this.closeWechatModal()
        // 跳转到身份选择页面
        this.$router.push('/identity')
      }, 1000)
    }
  },
  mounted() {
    // 检查URL参数，处理微信登录回调或错误
    const urlParams = new URLSearchParams(window.location.search)
    const error = urlParams.get('error')
    if (error) {
      ElMessage.error(decodeURIComponent(error))
      // 清除URL参数
      window.history.replaceState({}, document.title, window.location.pathname)
    }
    
    // 如果微信登录成功，尝试自动打开弹窗并检查状态
    const wechatSuccess = urlParams.get('wechat_success')
    const state = urlParams.get('state')
    if (wechatSuccess === 'true' && state) {
      this.qrCodeToken = state
      this.showWechatModal = true
      this.scanStatus = 'scanned'
      // 立即检查状态
      this.checkWechatStatus()
      // 清除URL参数
      window.history.replaceState({}, document.title, window.location.pathname)
    }
  },
  watch: {
    // 切换登录方式时清空表单
    loginMethod(newMethod) {
      if (newMethod === 'sms') {
        this.passwordPhone = ''
        this.password = ''
      } else {
        this.phone = ''
        this.smsCode = ''
      }
    }
  },
  beforeUnmount() {
    // 组件销毁时清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
    if (this.pollTimer) {
      clearInterval(this.pollTimer)
    }
  }
}
</script>
<style scoped>
.gradient-bg {
  background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
  position: relative;
  overflow: hidden;
}
.gradient-bg::before {
  content: '';
  position: absolute;
  width: 600px;
  height: 600px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  top: -200px;
  right: -100px;
}
</style>